<script setup lang="ts">
import { Check,Delete,Edit,Message,Search,Star,} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getHost ,getCompanyName , addHost,startHost,stopHost,deleHost,findByIdHost,findOneCompanyName,updatehost} from '@/api/HostManager';
import { onMounted, reactive ,ref  } from 'vue';
import { Row } from 'element-plus/es/components/table-v2/src/components/index.mjs';
// import { ComponentSize, FormInstance, FormRules } from 'element-plus'

//删除弹出框
const dele =(id:number) => {
    ElMessageBox.confirm(
    '确定要删除该企业?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleHost(id)
      await getInfo()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
};
//停用弹出框
const stop = (id:number) => {
    ElMessageBox.confirm(
    '确定要停用该企业?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await stopHost(id)
      await getInfo()
      ElMessage({
        type: 'success',
        message: '停用成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
};

//重启弹出框
const start = (id:number) => {
    ElMessageBox.confirm(
    '确定要重启该企业?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await startHost(id)
      await getInfo()
      ElMessage({
        type: 'success',
        message: '重启成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
};


//分页参数信息

var dataInfo= reactive({
   tableData:[
  {
    companyName:'',
    id: '1',
    companyId:'',
    sn: '',
    hostMoudel:'',
    name: '',
    state: '',
    sim: '',
    work: ''
  }
],
  pageInfo:{
    pageNum:1,
    pageSize:10,
    // word:""
  },
  total:ref(50)
})  

//分页相关函数
  const getPage = (newPage:any) => {
    dataInfo.pageInfo.pageNum = newPage;
    console.log(`当前页码已变更为: ${newPage}`);
};


//新增二级弹窗
var dialogFormVisible = ref(false)
var updateFormVisible = ref(false)
const formLabelWidth = '70px'

//定义表单数据类型
interface form {
  id:number,
  sn: string;
  state: number|string;
  companyName: string;
  warehouseId: number;
  companyId: number;
  hostModel: string;
  sim: string;
  name: string;
}

//新增表单
var form = reactive<form>({
    id:0,
    sn: '',
  state: '',
  companyName: '',
  warehouseId:0,
  companyId:0,
  hostModel:'',
  sim:'',
  name:''
//   delivery: false,
//   type: [],
//   resource: '',
//   desc: '',
})

//新增企业获取
var companyNameAdd = reactive([
  {address: "中国山东",admin: "",
adminPhone: "",
companyPrincipal: "",
companyType: "快递",
createTime: "2022-03-23T05:08:28.000+00:00",
id: 1,
name: "顺丰产业",
phone: "",
principalPhone: "",
remark: "",
shortName: "顺丰产业",
sn: "HE9464HR94YO",
updateTime: "2022-03-29T00:59:35.000+00:00",
website: ""}
])


//设置新增弹框必填项规则
const formRules = {
  name: [
    { required: true, message: '企业名称为必填项', trigger: 'blur' }
  ],
  sn: [
    { required: true, message: '企业名称为必填项', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '企业名称为必填项', trigger: 'blur' }
  ],
  hostModel: [
    { required: true, message: '企业名称为必填项', trigger: 'blur' }
  ],
  state: [
    { required: true, message: '状态为必填项', trigger: 'blur' },
  ],
  sim: [
    { required: true, message: '状态为必填项', trigger: 'blur' },
  ]
};
// 定义表单引用
const formRef = ref(null);

//新增相关函数
function add(){
            form.name = ''
            form.state = ''
            form.companyName = ''
            form.sn = ""
            form.hostModel = ''
            form.sim = ''
    dialogFormVisible.value = true;
}
const addok = () => {
    dialogFormVisible.value = false;
    formRef.value.validate (async(valid: any) => {
        if (valid) {
            console.log('表单校验通过，提交数据：', form);
            // 这里可以添加实际的提交逻辑，如发送请求等
            for(var i=0;i<=Object.keys(companyNameAdd[0]).length;i++){
              console.log(companyNameAdd);
              if(companyNameAdd[i].name === form.companyName){
                form.companyId = companyNameAdd[i].id
                break
              }
            }
            if(form.state == '停用'){
              form.state = 1
            }else{
              form.state = 0
            }
            await addrequest(form)
            console.log(form);
            form.name = ''
            form.state = ''
            form.companyName = ''
            form.sn = ""
            form.hostModel = ''
            form.sim = ''

        } else {
            console.log('表单校验不通过');
            return false;
        }
    });
};
//发送新增请求
async function addrequest(hostAddDTO:any){
var a = await addHost(hostAddDTO);
}

//修改二级弹窗
var dialogFormVisibleUpdate = ref(false)
function update(id: number) {
  form.id = id
  var data = findByIdHost(id);
  
  //取出promis对象中的数据
  data.then(async (result) => {
    console.log(result); // 
    console.log(result.data.data);
    form.name = result.data.data.name
    form.sim = result.data.data.sim
    form.sn = result.data.data.sn
    form.state = result.data.data.state
    form.hostModel = result.data.data.hostModel
    var { data: { data } } = await findByIdHost(id);
    var a = await findOneCompanyName(data.companyId)
    form.companyName = a.data
  });
  
  dialogFormVisibleUpdate.value = true;
}

const updateok = () => {
  dialogFormVisibleUpdate.value = false;
    formRef.value.validate (async(valid: any) => {
        if (valid) {
            console.log('表单校验通过，提交数据：', form);
            // 这里可以添加实际的提交逻辑，如发送请求等
            for(var i=0;i<=Object.keys(companyNameAdd[0]).length;i++){
              console.log(companyNameAdd);
              if(companyNameAdd[i].name === form.companyName){
                form.companyId = companyNameAdd[i].id
                break
              }
            }
            if(form.state == '停用'){
              form.state = 1
            }else{
              form.state = 0
            }
            console.log(form);
            await updatehost(form)

        } else {
            console.log('表单校验不通过');
            return false;
        }
    });
};

//失去焦点函数  
async function handleBlur(){
    console.log(dataInfo.pageInfo.word);
    getInfo()
}

// 请求方法
async function getInfo() {
  var { data: { data } } = await getHost(dataInfo.pageInfo)
  dataInfo.tableData = data.rows
  dataInfo.total = data.total
  for (var i = 0; i < data.rows.length; i++) {
    if (data.rows[i].state == 1) {
      dataInfo.tableData[i].state = "停用"
    } else {
      dataInfo.tableData[i].state = "启用"
    }
  }
  //获取企业名称请求
  var {data:{data}} = await getCompanyName();
  companyNameAdd = data.rows
  console.log(data.rows)
  
  console.log(data);
}


// 挂载函数
onMounted(() => {
 getInfo();
});

</script>

<template>
  <!-- 搜索框 -->
  <el-input class="input" style="width: 240px" placeholder="请输入企业名称" v-model="dataInfo.pageInfo.word"
    @blur="handleBlur" />

  <!-- 新增按钮 -->
  <div class="mb-4">
    <el-button plain @click="add">+新增</el-button>
  </div>



  <!-- 新增二级弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="新增主机" width="900" height="300">

    <el-row>
      <el-col :span="Number('12')">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="企业名称" prop="companyName">
            <el-select v-model="form.companyName" placeholder="请选择企业" class="i-input">
              <el-option :label=key.name :value=key.name v-for="key in companyNameAdd" :key="key" />
            </el-select>
          </el-form-item>
        </el-form>

      </el-col>
      <el-col :span="Number('12')">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="状态" prop="state">
            <el-select v-model="form.state" placeholder="请选择状态" class="i-input">
              <el-option label="停用" value="停用" />
              <el-option label="启用" value="启用" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="Number('12')">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="主机编号" prop="sn">
            <el-input v-model="form.sn" placeholder="请输入" class="i-input"></el-input>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="Number('12')">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="主机名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入" class="i-input"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="Number('12')">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="设备型号" prop="hostModel">
            <el-input v-model="form.hostModel" placeholder="请输入" class="i-input"></el-input>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="Number('12')">
        <el-form :model="form" :rules="formRules" ref="formRef">
          <el-form-item label="sim卡号" prop="sim">
            <el-input v-model="form.sim" placeholder="请输入" class="i-input"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 新增确认框 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addok">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改二级弹窗 -->
  <el-dialog v-model="dialogFormVisibleUpdate" title="修改主机" width="900" height="300">

<el-row>
  <el-col :span="Number('12')">
    <el-form :model="form" :rules="formRules" ref="formRef">
      <el-form-item label="企业名称" prop="companyName">
        <el-select v-model="form.companyName" placeholder="请选择企业" class="i-input">
          <el-option :label=key.name :value=key.name v-for="key in companyNameAdd"/>
        </el-select>
      </el-form-item>
    </el-form>

  </el-col>
  <el-col :span="Number('12')">
    <el-form :model="form" :rules="formRules" ref="formRef">
      <el-form-item label="状态" prop="state">
        <el-select v-model="form.state" placeholder="请选择状态" class="i-input">
          <el-option label="停用" value="停用" />
          <el-option label="启用" value="启用" />
        </el-select>
      </el-form-item>
    </el-form>
  </el-col>
</el-row>
<el-row>
  <el-col :span="Number('12')">
    <el-form :model="form" :rules="formRules" ref="formRef">
      <el-form-item label="主机编号" prop="sn">
        <el-input v-model="form.sn" placeholder="请输入" class="i-input"></el-input>
      </el-form-item>
    </el-form>
  </el-col>

  <el-col :span="Number('12')">
    <el-form :model="form" :rules="formRules" ref="formRef">
      <el-form-item label="主机名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" class="i-input"></el-input>
      </el-form-item>
    </el-form>
  </el-col>
</el-row>

<el-row>
  <el-col :span="Number('12')">
    <el-form :model="form" :rules="formRules" ref="formRef">
      <el-form-item label="设备型号" prop="hostModel">
        <el-input v-model="form.hostModel" placeholder="请输入" class="i-input"></el-input>
      </el-form-item>
    </el-form>
  </el-col>

  <el-col :span="Number('12')">
    <el-form :model="form" :rules="formRules" ref="formRef">
      <el-form-item label="sim卡号" prop="sim">
        <el-input v-model="form.sim" placeholder="请输入" class="i-input"></el-input>
      </el-form-item>
    </el-form>
  </el-col>
</el-row>

<!-- 修改确认框 -->
<template #footer>
  <div class="dialog-footer">
    <el-button @click="dialogFormVisibleUpdate = false">取消</el-button>
    <el-button type="primary" @click="updateok()">
      确认
    </el-button>
  </div>
</template>
</el-dialog>




  <!-- 信息表格 -->
  <el-table :data="dataInfo.tableData" style="width: 100%">
    <el-table-column prop="id" label="序号" width="180px" />
    <el-table-column prop="companyName" label="企业名称" width="180" />
    <el-table-column prop="sn" label="主机编号" />
    <el-table-column prop="name" label="主机名称" />
    <el-table-column prop="state" label="状态" />
    <el-table-column prop="hostModel" label="设备型号" />
    <el-table-column prop="sim" label="sim卡号" />
    <el-table-column label="操作" width="300">
      <template #default="{ row }">
         <router-link to="instrumentManagement">
        <a href="">仪表管理</a>
      </router-link>
      <a href="javascript:void(0)"@click="update(row.id)">修改</a>
      <a href="javascript:void(0)" @click="stop(row.id)">停用</a>
      <a href="javascript:void(0)" @click="dele(row.id)">删除</a>
      <a href="javascript:void(0)"@click="start(row.id)">重启</a>
      </template>
      <!-- scope.row 表示当前行的数据 -->
    </el-table-column>
  </el-table>

  <!-- 分页部分 -->
  <div class="example-pagination-block">
    <el-pagination background layout="prev, pager, next" :total="dataInfo.total" @click="getPage" />
  </div>


</template>

<style scoped>
/* 分页样式 */
.example-pagination-block {
  margin-top: 10px;
  float: right;
}
a {
color: blue;
margin-left: 7px;
font-size: 17px;
}
.mb-4{
    display: inline-block;
    margin: 5px;
    float:right;
}
.input {
    display: inline-block;
    margin: 5px;
    float: right;
}


.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}
.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
.i-input{
width: 200px;
}
</style>